import { parse } from 'querystring';
import React, { createContext, useState } from 'react';

import Storage from '@/application/utils/storage';
import { DialogContent } from '@/components/Dialog';
import { CardDialog } from '@/pages/Home/components/CardDialog';
import { User, UserLoginParams } from '@/types/user';

import { commonApi } from '../apis/home';

interface UserContextValue {
  /**
   * 当前登录的用户
   *
   * 未登录时为 `null`
   */
  user: User | null;
  logout?: () => void;
  /**
   * 登录
   */
  login?: () => Promise<void>;

  loginAsync?: (params: UserLoginParams) => Promise<void>;
}

export const UserContext = createContext<UserContextValue>({
  user: null
});

interface UserProviderProps {
  children: React.ReactNode;
}

/**
 * 用户状态上下文
 *
 * 并且会将用户状态持久化在localStorage中
 */
export const UserProvider: React.FC<UserProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);

  const login = async () => {
    const res: any = window.location.search.replace('?', '');
    const { activityId = 1 } = parse(res);
    try {
      let pas = {
        redirectUrl: parse(res)?.activityId
          ? `${window.location.origin}/?activityId=${activityId}`
          : `${window.location.origin}`,
        isLogin: '1'
      };
      pas = encodeURIComponent(JSON.stringify(pas)) as any;
      const url = `szbsales://web/redirect?appId=20210022&url=/pages/thirdTranSit/thirdTranSit&params=${pas}`;
      $Fw.navigateBack({
        delta: 1
      });
      window.location.href = url;
    } catch (e) {
      Storage.login.set(null);
      setUser(null);
    }
  };

  const loginAsync = async (params: UserLoginParams) => {
    try {
      const res = await commonApi.login(params, { hideToast: true });
      const m1 = true;
      // await apiActivityParticipableByGet();
      setUser({ m1Status: m1, ...res });
      Storage.login.set(res);
    } catch (e) {
      Storage.login.set(null);
      setUser(null);
      login();
    }
  };
  /** 校验用户是否可以参加活动 */
  const checkM1 = async () => {
    try {
      if (!user?.m1Status)
        CardDialog.show({
          children: <DialogContent title="无法参与活动" subTitle="您暂不符合活动参与条件哦" />
        });
    } catch (e) {
      console.log(e);
    }
  };
  const logout = () => {
    setUser(null);
    Storage.login.set(null);
  };

  return (
    <UserContext.Provider value={{ user, login, logout, loginAsync }}>
      {children}
    </UserContext.Provider>
  );
};
